package com.newfiber.common.core.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateRange;
import cn.hutool.core.date.DateTime;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author newfiber
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    public final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public final static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");

    public final static SimpleDateFormat ym = new SimpleDateFormat("yyyy-MM");
    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate(){
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate(){
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime(){
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow(){
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format){
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date){
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date){
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts){
        try{
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath(){
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime(){
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str){
        if (str == null){
            return null;
        }
        try{
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e){
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate(){
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static Map<String,Object> getDatePoor(Date endDate, Date nowDate){
        Map<String,Object> result=new HashMap<>();
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;

        result.put("day",day);
        result.put("hour",hour);
        result.put("min",min);
        result.put("time",(day>0?(day + "天"):"") + (hour>0?hour + "小时":"") + min + "分钟");
        return result;
    }

    /**
     * 分钟时间差转换
     */
    public static String getDayTimeChange(Long time){

        long nd =  24 * 60 ;
        long nh =  60 ;
        long nm =  60;

        long day = time / nd;
        long hour = time % nd / nh;
        long min = time % nd % nh;

        String result=(day>0?(day + "天"):"") + (hour>0?hour + "小时":"") + min + "分钟";
        return result;
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor){
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor){
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

	/**
	 * 创建日期范围生成器
	 *
	 * @param start 起始日期时间
	 * @param end   结束日期时间
	 * @param unit  步进单位
	 * @return {@link DateRange}
	 */
	public static List<DateTime> rangeToList(Date start, Date end, final DateField unit, int step) {
		return CollUtil.newArrayList((Iterable<DateTime>) new DateRange(start, end, unit, step));
	}

    /**
     * 获取对应时间最早的日期
     * @param time
     * @return
     */
    public static Date beginTimeByDate(Date time){
        LocalDate localDate = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        return toDate(LocalDateTime.of(localDate, LocalTime.MIN));
    }

    /**
     * 获取对应时间最早的日期
     * @param time
     * @return
     */
    public static Date endTimeByDate(Date time){
        LocalDate localDate = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        return toDate(LocalDateTime.of(localDate, LocalTime.MAX));
    }

    public static Integer getHours(Date time){
        return Integer.parseInt(new SimpleDateFormat("HH").format(time));
    }

    public static Integer interval(Date endTime,Date startTime){
       return (int) (endTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toEpochDay()-startTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toEpochDay());
    }

	/**
	 * TItle:将时间转为 对应小时的起始时间
	 */
	public static Date getDateStartHours(Date dateTime){
		String formatDate = DateUtils.parseDateToStr( "yyyy-MM-dd HH",dateTime);
		return DateUtils.parseDate(formatDate + ":00:00");
	}

	/**
	 * Title:生成当前日期对应的24小时时段数据
	 */
	public static List<Date> getTimeList(Date time){
		time=DateUtils.beginTimeByDate(time);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(time);
		calendar.add(Calendar.HOUR,8);
		time=calendar.getTime();
		List<Date> times=new ArrayList<>();
		int size=24;
		//获取当天24小时整点
		for (int i = 0; i < size; i++) {
			calendar.setTime(time);
			calendar.add(Calendar.HOUR,i);
			times.add(calendar.getTime());
		}
		return times;
	}

	/**
	 * 某个日期加分钟之后的时间
	 * @param date,min
	 * @return datetime
	 */
	public static String minConvertHourAfteDate(Date date, Integer min) {
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MINUTE, min);
		return sdf.format(calendar.getTime());
	}

	/**
	 * 分钟转时分数据
	 * @param min
	 */
	public static String minConvertHourMinSecond(Integer min) {
		String result = "";
		if (min != null) {
			Integer m = min;
			String format;
			Object[] array;
			Integer days = m / (60 * 24);
			Integer hours = m / (60) - days * 24;
			Integer minutes;
			if (days > 0) {
				hours += days * 24;
				minutes = m - hours * 60;
			}else{
				minutes = m - hours * 60 - days * 24 * 60;
			}
			String hoursstr;
			String minutesstr;
			if(hours < 10){
				hoursstr = "0"+hours;
			}else {
				hoursstr = hours + "";
			}
			if(minutes < 10){
				minutesstr="0"+minutes;
			}else {
				minutesstr = minutes + "";
			}
			format = "%1$s:%2$s";
			array = new Object[]{hoursstr, minutesstr};
			result = String.format(format, array);
		}
		return result;
	}
}
